package com.mzj.saas.jobs.lock.service.ruanku;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.commons.Constant;
import com.mzj.saas.commons.enums.LockCallBackTypeEnum;
import com.mzj.saas.jobs.backlog.entity.SmartLock;
import com.mzj.saas.jobs.backlog.repository.SmartLockRepository;
import com.mzj.saas.jobs.bill.entity.LockFrozen;
import com.mzj.saas.jobs.bill.entity.SmartLockAuth;
import com.mzj.saas.jobs.bill.entity.SmartLockCard;
import com.mzj.saas.jobs.bill.entity.SmartLockPwd;
import com.mzj.saas.jobs.bill.repository.*;
import com.mzj.saas.jobs.lock.repository.LockHouseSettingRepository;
import com.mzj.saas.jobs.lock.service.sgin.LockUtils;
import com.mzj.saas.jobs.lock.vo.LockCallBackVO;
import com.mzj.saas.jobs.lock.vo.yaluete.SmartLockVO;
import com.mzj.saas.jobs.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 软库-智能锁回调处理
 *
 * @author hp
 */
@Service
public class LockCallBackHandleService {

    private static final Logger log = LoggerFactory.getLogger(LockCallBackHandleService.class);
    private static final String cardSql = "SELECT c.lock_auth_id AS authId FROM saas_smart_lock_card c "
            + "LEFT JOIN saas_smart_lock_auth a ON c.lock_auth_id = a.id WHERE a.lock_id = ?";

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SmartLockService smartLockService;
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private LockFrozenRepository lockFrozenRepository;
    @Autowired
    private LockHouseSettingRepository lockHouseSettingRepository;
    @Autowired
    @Qualifier("redisTemplate")
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HouseRepository houseRepository;

    /**
     * 添加普通或者次数密码回调
     *
     * @param vo
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void addPwdCallBack(LockCallBackVO vo) {
        log.info("软库, 添加普通或者次数密码回调 vo={}", JSON.toJSONString(vo));
        try {

            JSONObject result = JSONObject.parseObject(LockUtils.toString(vo.getResult()));
            // 0：待执行；1：已成功；2：已失败
            Integer code = Integer.parseInt(result.get("code").toString());
            String desc = result.getString("desc");

            log.info("添加普通或者次数密码回调  sn={}, callBackId={}, code={}, desc={}", vo.getSn(), vo.getCallBackId(), code,
                    desc);

            // 查询执行缓存数据
            SmartLockVO lock = redisService.getLockCallBack(vo.getSn() + "_" + vo.getCallBackId());
            if (lock == null) {
                log.warn("添加普通或者次数密码回调 请求非法  sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(),
                        code, desc);
                return;
            }

            // 临时密码不处理用户授权业务
            if (lock.getPasswordType() != null && lock.getPasswordType() == 2) {
                log.info("临时密码回调 sn={}", vo.getSn());
                // 更新锁设置表状态
                lockHouseSettingRepository.updatePwdStatus(code, null, vo.getSn());
            } else {
                // 智能锁用户授权明细
                SmartLockAuth auth = smartLockAuthRepository.findSmartLockAuthById(lock.getAuthInfoId());

                if (auth == null) {
                    log.warn("添加普通或者次数密码回调  未找到智能锁用户授权明细   sn={}, callBackId={}, authId={},", vo.getSn(),
                            vo.getCallBackId(), lock.getAuthInfoId());
                    return;
                }

                // 更新智能锁用户授权明细
                if (code == 1 && auth.getPwdStatus() != 1) {
                    auth.setPwdStatus(1);
                    smartLockAuthRepository.save(auth);
                }
                // 密码授权-授权类型明细
                SmartLockPwd lockPwd = smartLockPwdRepository.findByLockAuthId(auth.getId());

                if (lockPwd == null) {
                    log.warn("添加普通或者次数密码回调  未找到密码授权-授权类型明细  sn={}, callBackId={}, authId={}", vo.getSn(),
                            vo.getCallBackId(), auth.getId());
                    return;
                }

                // 更新密码授权-授权类型明细
                lockPwd.setStatus(code);
                lockPwd.setLastUpdateTime(new Date());
                smartLockPwdRepository.save(lockPwd);
            }

            if (code == 2) {
                // 执行失败操作
                torepeat(vo, lock, LockCallBackTypeEnum.ADD_PWD.toString());
            }
            redisService.delLockClassBack(vo.getSn() + "_" + vo.getCallBackId(), lock);
        } catch (Exception e) {
            log.error("添加普通或者次数密码回调异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 冻结或解冻密码回调
     *
     * @param vo
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void freezeOrUnfreezeCallBack(LockCallBackVO vo) {
        log.info("软库, 冻结或解冻密码回调, vo={}", JSON.toJSONString(vo));
        try {

            JSONObject result = JSONObject.parseObject(LockUtils.toString(vo.getResult()));
            Integer code = Integer.parseInt(result.get("code").toString());
            String desc = result.getString("desc");

            SmartLockVO lockVo = redisService.getLockCallBack(vo.getSn() + "_" + vo.getCallBackId());

            if (lockVo == null) {
                log.warn("冻结或解冻密码回调 请求非法  sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(),
                        code, desc);
                return;
            }

            log.info("冻结或解冻密码回调 type={}, sn={}, callBackId={}, code ={}, desc={}, lockVo={}",
                    lockVo.getSuspend() == 1 ? "冻结" : "解冻", vo.getSn(), vo.getCallBackId(), code, desc,
                    JSON.toJSONString(lockVo));

            // 智能锁用户授权明细
            SmartLockAuth auth = smartLockAuthRepository.findSmartLockAuthById(lockVo.getAuthInfoId());
            // 密码授权-授权类型明细
            SmartLockPwd lockPwd = smartLockPwdRepository.findByLockAuthId(lockVo.getAuthInfoId());
            lockPwd.setStatus(code);

            Optional<SmartLock> smartLockOptional = smartLockRepository.findById(auth.getLockId());
            if (!smartLockOptional.isPresent()) {
                log.info("冻结或解冻密码回调 智能锁不存在 sn={}", vo.getSn());
                return;
            }
            SmartLock smartLock = smartLockOptional.get();

            // 冻结（1）或者解冻（0)
            // 0：待执行；1：已成功；2：已失败
            // 更新智能锁用户授权明细
            // 更新密码授权-授权类型明细
            if (code == 1) {
                // 冻结
                if (lockVo.getSuspend() == 1) {
                    auth.setPwdStatus(2);
                }
                // 解冻
                if (lockVo.getSuspend() == 0) {
                    auth.setPwdStatus(1);

                    // 智能锁设备状态更新为正常
                    smartLock.setMechineStatus(1);
                    smartLockRepository.save(smartLock);

                    // 任意授权解冻时, 更新公租房锁授权状态
                    String houseId = smartLock.getHouseId();
                    houseRepository.updateLockStatusById(houseId, 1);
                }
                smartLockAuthRepository.save(auth);

                // 冻结检查是否全部冻结，更新智能锁设备状态
                if (lockVo.getSuspend() == 1) {
                    if (smartLock.getBindType() == 1) {
                        int authCount = smartLockAuthRepository.findSmartLockAuthByLockId(auth.getLockId());
                        List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(auth.getLockId(), 0);
                        if (authCount == auths.size()) {
                            smartLock.setMechineStatus(2);
                            smartLockRepository.save(smartLock);

                            // 全部冻结时, 更新公租房锁授权状态
                            String houseId = smartLock.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 4);
                        }
                    } else {
                        int authCount = smartLockAuthRepository.findPersonSmartLockAuthByLockId(auth.getLockId());
                        List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(auth.getLockId(), 1);
                        if (authCount == auths.size()) {
                            smartLock.setMechineStatus(2);
                            smartLockRepository.save(smartLock);

                            // 全部冻结时, 更新公租房锁授权状态
                            String houseId = smartLock.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 4);
                        }
                    }
                }
            }
            smartLockPwdRepository.save(lockPwd);

            if (lockVo.getSuspend() == 1) {
                // 更新智能锁冻结记录
                Optional<LockFrozen> frozenOpt = lockFrozenRepository.findById(lockVo.getLockFrozenId());

                if (frozenOpt.isPresent()) {
                    LockFrozen frozen = frozenOpt.get();
                    frozen.setPwdStatus(code);
                    lockFrozenRepository.save(frozen);
                }
            }

            if (code == 2) {
                // 执行失败操作
                torepeat(vo, lockVo, LockCallBackTypeEnum.FREEZE_QR_UNFREEZE.toString());
            }
            redisService.delLockClassBack(vo.getSn() + "_" + vo.getCallBackId(), lockVo);

            // 删除冻结/解冻操作redis缓存
            redisTemplate.delete("lock_id:" + auth.getLockId());

        } catch (Exception e) {
            log.error("冻结或解冻密码回调异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 删除普通或者次数密码回调
     *
     * @param vo
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void clearPwdCallBack(LockCallBackVO vo) {
        log.info("软库, 删除普通或者次数密码回调, vo={}", JSON.toJSONString(vo));
        try {

            JSONObject result = JSONObject.parseObject(LockUtils.toString(vo.getResult()));

            Integer code = Integer.parseInt(result.get("code").toString());
            String desc = result.getString("desc");

            log.info("删除普通或者次数密码回调 , sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(), code,
                    desc);

            SmartLockVO lockVo = redisService.getLockCallBack(vo.getSn() + "_" + vo.getCallBackId());

            if (lockVo == null) {
                log.warn("删除普通或者次数密码回调, 请求非法  sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(),
                        code, desc);
                return;
            }

            // 0：待执行；1：已成功；2：已失败
            if (code == 1) {

                // 智能锁用户授权明细
                SmartLockAuth auth = smartLockAuthRepository.findSmartLockAuthById(lockVo.getAuthInfoId());
                // 密码授权-授权类型明细
                SmartLockPwd lockPwd = smartLockPwdRepository.findByLockAuthId(lockVo.getAuthInfoId());

                // 删除密码授权-授权类型明细
                if (lockPwd != null) {
                    smartLockPwdRepository.delete(lockPwd);
                }
                if (auth != null) {
                    auth.setPwdStatus(0);

                    // 智能锁用户授权明细
                    smartLockAuthRepository.save(auth);
                } else {
                    log.info("删除普通或者次数密码回调 , 锁信息不存在, authInfoId={}", lockVo.getAuthInfoId());
                }

            }

            if (code == 2) {
                // 执行失败操作
                torepeat(vo, lockVo, LockCallBackTypeEnum.CLEAR_PWD.toString());
            }
            redisService.delLockClassBack(vo.getSn() + "_" + vo.getCallBackId(), lockVo);
        } catch (Exception e) {
            log.error("删除普通或者次数密码回调异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 删除所有密码回调
     *
     * @param vo
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void clearAllPwdCallBack(LockCallBackVO vo) {
        log.info("软库, 删除所有密码回调 vo={}", JSON.toJSONString(vo));
        try {
            JSONObject result = JSONObject.parseObject(LockUtils.toString(vo.getResult()));

            Integer code = Integer.parseInt(result.get("code").toString());
            String desc = result.getString("desc");

            log.info("删除所有密码回调  sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(), code, desc);

            SmartLockVO lockVo = redisService.getLockCallBack(vo.getSn() + "_" + vo.getCallBackId());

            if (lockVo == null) {
                log.warn("删除所有密码回调 请求非法  sn={}, callBackId={}, code={}, desc={}", vo.getSn(), vo.getCallBackId(), code,
                        desc);
                return;
            }

            // 0：待执行；1：已成功；2：已失败
            if (code == 1) {
                SmartLock lock = smartLockRepository.findBySn(vo.getSn());

                List<SmartLockPwd> lockPwd = smartLockPwdRepository.findByLockId(lock.getId());
                smartLockPwdRepository.deleteAll(lockPwd);

                List<Long> authIds = lockPwd.stream().map(SmartLockPwd::getLockAuthId).collect(Collectors.toList());

                List<SmartLockAuth> authList = (List<SmartLockAuth>) smartLockAuthRepository.findAllById(authIds);

                smartLockAuthRepository.deleteAll(authList);
            }

            if (code == 2) {
                // 执行失败操作
                torepeat(vo, lockVo, LockCallBackTypeEnum.CLEAR_ALL_PWD.toString());
            }
            redisService.delLockClassBack(vo.getSn() + "_" + vo.getCallBackId(), lockVo);
        } catch (Exception e) {
            log.error("删除所有密码回调异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 添加卡回调
     *
     * @param vo
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void addCardCallBack(LockCallBackVO vo) {
        log.info("软库, 添加卡回调, vo={}", JSON.toJSONString(vo));
        try {
            JSONObject result = JSONObject.parseObject(LockUtils.toString(vo.getResult()));

            Integer code = Integer.parseInt(result.get("code").toString());
            String desc = result.getString("desc");

            log.info("添加卡回调  sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(), code, desc);

            SmartLockVO lockVo = redisService.getLockCallBack(vo.getSn() + "_" + vo.getCallBackId());

            if (lockVo == null) {
                log.warn("添加卡回调请求非法  sn={}, callBackId={}, code={}, desc={}", vo.getSn(), vo.getCallBackId(), code,
                        desc);
                return;
            }

            // 密码授权-授权类型明细
            SmartLockCard lockCard = smartLockCardRepository.findByLockAuthIdAndType(lockVo.getAuthInfoId(), lockVo.getCardType());
            lockCard.setStatus(code);
            lockCard.setLastUpdateTime(new Date());
            smartLockCardRepository.save(lockCard);
            // 0：待执行；1：已成功；2：已失败
            if (code == 1) {
                // 智能锁用户授权明细
                SmartLockAuth auth = smartLockAuthRepository.findSmartLockAuthById(lockVo.getAuthInfoId());
                if (lockVo.getCardType() == 1) {
                    auth.setCardStatus(code);
                }
                if (lockVo.getCardType() == 2) {
                    auth.setCpuStatus(code);
                }
                smartLockAuthRepository.save(auth);
            }

            if (code == 2) {
                // 执行失败操作
                torepeat(vo, lockVo, LockCallBackTypeEnum.ADD_CARD.toString());
            }
            redisService.delLockClassBack(vo.getSn() + "_" + vo.getCallBackId(), lockVo);
        } catch (Exception e) {
            log.error("添加卡回调异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 冻结或解冻卡回调
     *
     * @param vo
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void freezeOrUnfreezeCardCallBack(LockCallBackVO vo) {
        log.info("软库, 冻结或解冻卡回调 vo={}", JSON.toJSONString(vo));
        try {

            JSONObject result = JSONObject.parseObject(LockUtils.toString(vo.getResult()));
            Integer code = Integer.parseInt(result.get("code").toString());
            String desc = result.getString("desc");

            SmartLockVO lockVo = redisService.getLockCallBack(vo.getSn() + "_" + vo.getCallBackId());
            if (lockVo == null) {
                log.warn("冻结或解冻卡回调 请求非法  sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(), code,
                        desc);
                return;
            }

            log.info("冻结或解冻卡回调 type={}, sn={}, callBackId={}, cardType={}, code={}, desc={}, lockVo={}",
                    lockVo.getSuspend() == 1 ? "冻结" : "解冻", vo.getSn(), vo.getCallBackId(), lockVo.getCardType(), code,
                    desc, JSON.toJSONString(lockVo));

            // 智能锁用户授权明细
            SmartLockAuth auth = smartLockAuthRepository.findSmartLockAuthById(lockVo.getAuthInfoId());
            // 密码授权-授权类型明细
            SmartLockCard lockCard = smartLockCardRepository.findByLockAuthIdAndType(lockVo.getAuthInfoId(), lockVo.getCardType());

            Optional<SmartLock> smartLockOptional = smartLockRepository.findById(auth.getLockId());
            if (!smartLockOptional.isPresent()) {
                log.info("冻结或解冻卡回调 智能锁不存在 sn={}", vo.getSn());
                return;
            }
            SmartLock smartLock = smartLockOptional.get();

            // 冻结（1）或者解冻（0)
            // 0：待执行；1：已成功；2：已失败
            // 更新智能锁用户授权明细
            if (code == 1) {
                // 冻结
                if (lockVo.getSuspend() == 1) {
                    if (lockVo.getCardType() == 1) {
                        // 身份证
                        auth.setCardStatus(2);
                    } else if (lockVo.getCardType() == 2) {
                        // CPU卡
                        auth.setCpuStatus(2);
                    }
                }
                // 解冻
                if (lockVo.getSuspend() == 0) {
                    if (lockVo.getCardType() == 1) {
                        // 身份证
                        auth.setCardStatus(1);
                    } else if (lockVo.getCardType() == 2) {
                        // CPU卡
                        auth.setCpuStatus(1);
                    }

                    smartLock.setMechineStatus(1);
                    smartLockRepository.save(smartLock);

                    // 任意授权解冻时, 更新公租房锁授权状态
                    String houseId = smartLock.getHouseId();
                    houseRepository.updateLockStatusById(houseId, 1);
                }
                smartLockAuthRepository.save(auth);

                // 冻结检查是否全部冻结，更新智能锁设备状态
                if (lockVo.getSuspend() == 1) {
                    if (smartLock.getBindType() == 1) {
                        int authCount = smartLockAuthRepository.findSmartLockAuthByLockId(auth.getLockId());
                        List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(auth.getLockId(), 0);
                        if (authCount == auths.size()) {
                            smartLock.setMechineStatus(2);
                            smartLockRepository.save(smartLock);

                            // 全部冻结时, 更新公租房锁授权状态
                            String houseId = smartLock.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 4);
                        }
                    } else {
                        int authCount = smartLockAuthRepository.findPersonSmartLockAuthByLockId(auth.getLockId());
                        List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(auth.getLockId(), 1);
                        if (authCount == auths.size()) {
                            smartLock.setMechineStatus(2);
                            smartLockRepository.save(smartLock);

                            // 全部冻结时, 更新公租房锁授权状态
                            String houseId = smartLock.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 4);
                        }
                    }
                }
            }

            if (lockVo.getSuspend() == 1) {
                // 更新智能锁冻结记录
                Optional<LockFrozen> frozenOpt = lockFrozenRepository.findById(lockVo.getLockFrozenId());

                if (frozenOpt.isPresent()) {
                    LockFrozen frozen = frozenOpt.get();
                    frozen.setCardStatus(code);
                    lockFrozenRepository.save(frozen);
                }
            }

            if (lockCard != null) {
                lockCard.setStatus(code);
                lockCard.setLastUpdateTime(new Date());
                smartLockCardRepository.save(lockCard);
            }

            if (code == 2) {
                // 执行失败操作
                torepeat(vo, lockVo, LockCallBackTypeEnum.FREEZE_QR_UNFREEZE_CARD.toString());
            }
            redisService.delLockClassBack(vo.getSn() + "_" + vo.getCallBackId(), lockVo);

            // 删除冻结/解冻操作redis缓存
            redisTemplate.delete("lock_id:" + auth.getLockId());

        } catch (Exception e) {
            log.error("冻结或解冻密码回调异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 删除卡回调
     *
     * @param vo
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void clearCardCallBack(LockCallBackVO vo) {
        log.info("软库, 删除卡回调vo={}", JSON.toJSONString(vo));
        try {
            JSONObject result = JSONObject.parseObject(LockUtils.toString(vo.getResult()));

            Integer code = Integer.parseInt(result.get("code").toString());
            String desc = result.getString("desc");

            SmartLockVO lockVo = redisService.getLockCallBack(vo.getSn() + "_" + vo.getCallBackId());

            if (lockVo == null) {
                log.warn("删除卡回调请求非法  sn={}, callBackId={}, code={}, desc={}", vo.getSn(), vo.getCallBackId(), code,
                        desc);
                return;
            }

            log.info("删除卡回调  sn={}, callBackId={}, authInfoId={}, cardType={}, index={}, code ={}, desc={}", vo.getSn(),
                    vo.getCallBackId(), lockVo.getAuthInfoId(), lockVo.getCardType(), lockVo.getIndex(), code, desc);

            // 0：待执行；1：已成功；2：已失败
            if (code == 1) {
                // 删除卡
                SmartLockCard card = smartLockCardRepository.findByLockAuthIdAndTypeAndCardIndex(lockVo.getAuthInfoId(),
                        lockVo.getCardType(), lockVo.getIndex());

                if (card != null) {
                    smartLockCardRepository.delete(card);
                }

                Integer count = smartLockCardRepository.countByLockAuthId(lockVo.getAuthInfoId());

                if (count == null || count == 0) {
                    // 智能锁用户授权明细
                    SmartLockAuth auth = smartLockAuthRepository.findSmartLockAuthById(lockVo.getAuthInfoId());
                    if (auth != null) {
                        auth.setCardStatus(0);
                        smartLockAuthRepository.save(auth);
                    } else {
                        log.info("删除卡回调, 锁授权信息不存在, authInfoId={}", lockVo.getAuthInfoId());
                    }
                }
            }

            if (code == 2) {
                // 执行失败操作
                torepeat(vo, lockVo, LockCallBackTypeEnum.ADD_CARD.toString());
            }
            redisService.delLockClassBack(vo.getSn() + "_" + vo.getCallBackId(), lockVo);
        } catch (Exception e) {
            log.error("删除卡回调异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 删除所有卡回调
     *
     * @param vo
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void clearAllCardCallBack(LockCallBackVO vo) {
        log.info("软库, 删除所有卡回调, vo={}", JSON.toJSONString(vo));
        try {

            JSONObject result = JSONObject.parseObject(LockUtils.toString(vo.getResult()));

            Integer code = Integer.parseInt(result.get("code").toString());
            String desc = result.getString("desc");

            log.info("删除所有卡回调  sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(), code, desc);
            SmartLockVO lockVo = redisService.getLockCallBack(vo.getSn() + "_" + vo.getCallBackId());

            if (lockVo == null) {
                log.warn("删除所有卡回调请求非法  sn={}, callBackId={}, code ={}, desc={}", vo.getSn(), vo.getCallBackId(), code,
                        desc);
                return;
            }

            if (code == 1) {

                SmartLock lock = smartLockRepository.findBySn(vo.getSn());
                List<Map<String, Object>> list = jdbcTemplate.queryForList(cardSql, lock.getId());
                if (CollectionUtils.isEmpty(list)) {
                    return;
                }

                List<Long> authIds = list.stream().map(m -> Long.parseLong(m.get("authId").toString()))
                        .collect(Collectors.toList());

                List<SmartLockCard> cardList = smartLockCardRepository.findByLockAuthIdIn(authIds);
                smartLockCardRepository.deleteAll(cardList);
                List<SmartLockAuth> authList = (List<SmartLockAuth>) smartLockAuthRepository.findAllById(authIds);

                authList.forEach(a -> {
                    a.setCardStatus(0);
                    a.setCpuStatus(0);
                });
                smartLockAuthRepository.saveAll(authList);
            }
            if (code == 2) {
                // 执行失败操作
                torepeat(vo, lockVo, LockCallBackTypeEnum.ADD_CARD.toString());
            }
            redisService.delLockClassBack(vo.getSn() + "_" + vo.getCallBackId(), lockVo);
        } catch (Exception e) {
            log.error("删除所有卡回调异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 执行失败后重发机制
     *
     * @param vo
     * @param lock
     */
    private void torepeat(LockCallBackVO vo, SmartLockVO lock, String type) {
        try {
            LockCallBackTypeEnum typeEnum = LockCallBackTypeEnum.getLockType(vo.getCallBackType());
            String repeatNumStr = redisService.getValue(Constant.CALLBACK_REPEAT_NUM);

            if (StringUtils.isBlank(repeatNumStr)) {
                log.warn("{}, 执行失败, 次数不存在无需重复调用  sn={}, callBackId={},", typeEnum.getCallBackText(), vo.getSn(),
                        vo.getCallBackId());
                return;
            }

            Integer repeatNum = Integer.parseInt(repeatNumStr);

            if (repeatNum <= 0) {
                log.warn("{}, 执行失败, 次数小于等于0无需重复调用  sn={}, callBackId={}", typeEnum.getCallBackText(), vo.getSn(),
                        vo.getCallBackId());
                return;
            }

            Integer num = redisService.getRepeatLock(type, vo.getSn());

            if (num >= repeatNum) {
                log.warn("{}, 执行失败 , 重复调用已超次数无需重复调用  sn={}, callBackId={}", typeEnum.getCallBackText(), vo.getSn(),
                        vo.getCallBackId());
                return;
            }

            log.warn("{}, 执行失败, 将第{}次重新调用  sn={}, callBackId={}, code={},", typeEnum.getCallBackText(), num, vo.getSn(),
                    vo.getCallBackId());

            switch (typeEnum) {
                case ADD_PWD:
                    smartLockService.operationPassword(lock);
                    break;
                case FREEZE_QR_UNFREEZE:
                    smartLockService.freezeOrUnfreeze(lock);
                    break;
                case CLEAR_PWD:
                    smartLockService.clearPassword(lock);
                    break;
                case CLEAR_ALL_PWD:
                    smartLockService.clearAllPassword(lock);
                    break;
                case ADD_CARD:
                    smartLockService.operationCardPassword(lock);
                    break;
                case FREEZE_QR_UNFREEZE_CARD:
                    smartLockService.freezeOrUnfreezeCard(lock);
                    break;
                case CLEAR_CARD:
                    smartLockService.clearCard(lock);
                    break;
                case CLEAR_ALL_CARD:
                    smartLockService.clearAllCard(lock);
                    break;
                default:
                    break;
            }
            redisService.putRepeatLock(type, vo.getSn());
        } catch (Exception e) {
            log.error("重复发送异常" + e.getMessage(), e);
        }
    }
}
